﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using SwaggerDemo.Models;

namespace SwaggerDemo.Controllers;

/// <summary>
/// 账号管理
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class AccountController : ControllerBase {
  private readonly IConfiguration _connfig;

  public AccountController (IConfiguration config) {
    _connfig = config;
  }

  /// <summary>
  /// 用户注册
  /// </summary>
  /// <param name="model"></param>
  /// <returns></returns>
  [AllowAnonymous]
  [HttpPost("register")]
  public IActionResult Register ([FromForm] RegisterModel model) {
    if (!ModelState.IsValid) return BadRequest(ModelState);
    return Ok("注册成功");
  }

  /// <summary>
  /// 登录
  /// </summary>
  /// <param name="acc">账号</param>
  /// <returns></returns>
  [AllowAnonymous]
  [HttpPost("login")]
  public IActionResult Login ([FromBody] LoginModel acc) {
    if (!ModelState.IsValid) return BadRequest(ModelState);

    // if (string.IsNullOrEmpty(acc.Password) || string.IsNullOrEmpty(acc.Password))
    //     return BadRequest(new { code = 0, message = "请输入用户名和密码" });

    if (acc.UserName != "admin" || acc.Password != "123456")
      return BadRequest(new { code = 0, message = "账号错误，请重试" });

    var claims = new[]{
         new Claim(JwtRegisteredClaimNames.NameId, "10001"), //用户标识
         new Claim(JwtRegisteredClaimNames.Name, acc.UserName!),
         new Claim("Roles", "Admin"),
         new Claim(JwtRegisteredClaimNames.Nbf,
                            $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}")
     };

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_connfig["JwtOptions:SecretKey"]!));
    var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    _ = int.TryParse(_connfig["JwtOptions:SecretKey"], out var exp);
    var token = new JwtSecurityToken(
        issuer: _connfig["JwtOptions:Issuer"],
        audience: _connfig["JwtOptions:Audience"],
        claims: claims,
        expires: DateTime.Now.AddMinutes(exp),
        signingCredentials: credentials);

    return Ok(new {
      code = 1,
      message = "ok",
      token = new JwtSecurityTokenHandler().WriteToken(token)
    });
  }

  [Authorize]
  // [Authorize(Roles = "Admin")]
  [HttpPost("userinfo/{id}")]
  [ProducesResponseType(typeof(UserInfo), 200)]
  [ProducesResponseType(typeof(IDictionary<string, string>), 400)]
  public IActionResult UserInfo (int id = 1001) {
    if (id != 1001) return BadRequest(new { code = 0, message = "参数错误" });

    return Ok(new UserInfo
    {
      Id = 1001,
      Name = "Jack",
      Age = 120,
      Phone = "18200100001",
      Address = "BeiJing",
      Married = true,
      Email = "abc@gmail.com",
      Role = new[] { "Admin", "Developer" }
    });
  }

  /// <summary>
  /// 授权信息
  /// </summary>
  /// <returns></returns>
  [Authorize]
  [HttpGet("jwt")]
  public IActionResult JwtInfo () {
    var acc = new {
      ID = User.FindFirst(ClaimTypes.NameIdentifier)?.Value,
      Name = User.FindFirst(JwtRegisteredClaimNames.Name)?.Value,
      Roles = User.FindFirst("Roles")?.Value
    };
    return Ok(acc);
  }
}